const povertyReasonsColors = {
    "因病": "#ff9999",
    "因学": "#66b3ff",
    "因残": "#99ff99",
    "缺劳力": "#ffcc99",
    "缺资金": "#ff9966",
    "缺土地": "#66ff66",
    "缺技术": "#ff66cc",
    "因婚": "#ff6699",
    "因灾": "#cc99ff",
    "自身发展动力不足": "#ccccff",
    "缺水": "#99ccff",
    "因丧": "#ffccff",
    "其他": "#e0e0e0"
};

const height = 400;
const width = 250;
const innerRadius = 30;
const outerRadius = 100;

// 绘制村庄的饼状玫瑰图
function drawPieChartAtLocation(filteredData, lat, lon) {
    // 计算致贫原因
    let povertyReasonsCount = {};
    filteredData.forEach(function (d) {
        let reason = d["致贫原因1"];
        if (reason) {
            if (povertyReasonsCount[reason]) {
                povertyReasonsCount[reason]++;
            } else {
                povertyReasonsCount[reason] = 1;
            }
        }
    });

    let povertyReasonsArray = Object.entries(povertyReasonsCount).map(([key, value]) => ({
        reason: key,
        count: value
    }));

    // 使用极坐标系生成数据
    const radiusScale = d3.scaleLinear().domain([0, d3.max(povertyReasonsArray, d => d.count)]).range([innerRadius, outerRadius]);

    const pie = d3.pie().value(d => d.count).startAngle(0).endAngle(2 * Math.PI);

    const arcData = pie(povertyReasonsArray);
    const path = d3.arc().innerRadius(innerRadius).outerRadius(d => radiusScale(d.data.count));  // 缩小外半径
    const color = d3.scaleOrdinal().domain(Object.keys(povertyReasonsColors)).range(Object.values(povertyReasonsColors));

    // 创建一个SVG元素，并将其添加到地图上
    const svg = d3.select(map.getPanes().overlayPane)
        .append('svg')
        .attr('width', width)
        .attr('height', height)
        .style('position', 'absolute')
        .style('transform', `translate(-${width / 2}px, -${height / 2}px)`);

    const pieChartYTranslate = height / 2;

    const arcs = svg.selectAll('path')
        .data(arcData)
        .join('path')
        .attr('d', path)
        .attr('transform', `translate(${width / 2}, ${pieChartYTranslate})`)
        .attr('fill', d => color(d.data.reason))
        .attr('stroke', '#fff')
        .attr('stroke-width', 2)
        .style('opacity', 0)
        .transition()
        .duration(1000)
        .style('opacity', 1)  // 增加渐显效果
        .attrTween('d', function (d) {
            const i = d3.interpolate({ startAngle: 0, endAngle: 0 }, d);
            return function (t) {
                return path(i(t));
            };
        });

    // 将SVG图层定位到经纬度对应的位置
    const latLon = L.latLng(lat, lon);
    const point = map.latLngToLayerPoint(latLon);
    svg.style('left', `${point.x - width / 2}px`)
        .style('top', `${point.y - height / 2}px`);
}

// 读取村庄数据（包含经纬度和致贫原因）
d3.csv('./data/农户数据.csv').then(data => {
    allData = data;

    // 假设你有一个村庄经纬度数据对象 villageData
    const villageData = [
        { name: '村庄1', lat: 34.0522, lon: -118.2437 },  // 示例数据
        { name: '村庄2', lat: 35.0522, lon: -119.2437 },
        { name: '村庄3', lat: 36.0522, lon: -120.2437 },
        // 添加更多村庄数据
    ];

    // 为每个村庄添加饼状玫瑰图
    villageData.forEach(village => {
        let filteredData = allData.filter(d => d["行政村"] === village.name);
        drawPieChartAtLocation(filteredData, village.lat, village.lon);
    });

    drawLegend();  // 绘制图例
});

// 绘制图例
function drawLegend() {
    const legend = d3.select('#legend');
    legend.selectAll('*').remove();  // 清空之前的图例

    Object.entries(povertyReasonsColors).forEach(([reason, color]) => {
        const legendItem = legend.append('div').attr('class', 'legend-item');
        legendItem.append('div')
            .attr('class', 'legend-color-box')
            .style('background-color', color);
        legendItem.append('span').text(reason);
    });
}
